package com.celi.scs.common.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.celi.scs.common.constant.utils.DeptUtil;
import com.celi.scs.common.dao.SystemMapper;
import com.celi.scs.common.entity.DeptDTO;
import com.celi.system.dao.DeptRepository;
import com.celi.system.dao.UserDeptRepository;
import com.celi.system.dao.UserRepository;
import com.celi.system.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemService {


    @Autowired
    private SystemMapper systemMapper;


    @Value("${params.level1DeptCode}")
    private String level1DeptCode;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserDeptRepository userDeptRepository;


    /**
     * 查询一级机构
     * @return
     */
    public Dept findLevel1Dept() {
        return systemMapper.findLevel1Dept(level1DeptCode);
    }

    public List<DeptDTO> listDeptUsers() {

        // 1. 查询所有机构
        final List<Dept> depts = this.listDept();
        List<DeptDTO> deptDTOList = BeanUtil.copyToList(depts, DeptDTO.class);

        // 2. 查询所有人
        final List<User> users = userRepository.findAll();

        // 3. 查询所有机构和人员关系
        final List<UserDept> userDepts = userDeptRepository.findAll();

        for (DeptDTO deptDTO : deptDTOList) {
            deptDTO.setNickName(deptDTO.getDeptName());
            distributeUsersToChildren(deptDTO, users, userDepts);
        }
        return deptDTOList;
    }

    private static void distributeUsersToChildren(DeptDTO deptDTO, List<User> users, List<UserDept> userDepts) {
        if (deptDTO.getChildren() != null && !deptDTO.getChildren().isEmpty()) {
            final List<Dept> deptChildren = deptDTO.getChildren();
            List<DeptDTO> deptDTOS = BeanUtil.copyToList(deptChildren, DeptDTO.class);
            for (DeptDTO child : deptDTOS) {
                child.setNickName(child.getDeptName());
                final List<String> userIds = userDepts.stream().filter(ud -> ud.getDeptId().equals(child.getDeptId())).map(UserDept::getUserId).collect(Collectors.toList());
                final List<User> userList = users.stream().filter(user -> userIds.contains(user.getUserId())).collect(Collectors.toList());
                userList.forEach(u -> u.setDisabled(null));
            //    child.setUsers(userList);
                distributeUsersToChildren(child, users, userDepts);
            }
            deptDTO.setDeptDTOList(deptDTOS);
        }
    }



    public List<Dept> listDept() {
        List<Dept> deptList = deptRepository.findAll();
        //2. 机构整合
        List<Dept> list = deptList.stream()
                //2-1. 过滤一级机构
                .filter(dept -> StringUtils.isBlank(dept.getParentId()))
                //2-2. 排序
                .sorted((dept1, dept2) -> {
                    return (dept1.getOrderIndex() == null ? 0 : dept1.getOrderIndex()) - (dept2.getOrderIndex() == null ? 0 : dept2.getOrderIndex());
                })
                //2-3. 设置子机构
                .map(dept -> {
                    dept.setChildren(DeptUtil.recursion(dept, deptList));
                    return dept;
                })
                .collect(Collectors.toList());
        return list;

    }

    public List<User> listUserDeptByDeptIds(List<String> deptIds) {
        return systemMapper.listUserDeptByDeptIds(deptIds);
    }

    public List<UserDept> listDeptByUserId(String userId) {
        List<String> userIds = new ArrayList<>();
        if (StrUtil.isNotBlank(userId)) {
            userIds.add(userId);
        }
        return systemMapper.listDeptByUserIds(userIds);
    }

    // 根据userId和权限编码获取对应权限
    public List<Permission> listPermissionByUserIdAndPermission(String userId, List<String> permissionCodeList) {
        if (CollectionUtil.isEmpty(permissionCodeList) || StrUtil.isBlank(userId)) {
            return new ArrayList<>();
        }
        return systemMapper.listPermissionByUserIdAndPermission(userId, permissionCodeList);
    }
}
